package one.bugu.android.demon.ui.adapter.snatch;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.base.BaseListAdapter;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.snatch.SnatchPeriodBean;
import one.bugu.android.demon.common.MyBaseFragment;
import one.bugu.android.demon.ui.activity.snatch.SnatchDetailsActivty;
import one.bugu.android.demon.ui.fragment.snatch.BuyingFragment;
import one.bugu.android.demon.util.ColorUtil;
import one.bugu.android.demon.util.DateUtils;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.ScreenUtils;

/**
 * Description SnatchListAdapter 抢购中适配器
 *
 * @author liuxin
 * @date 2018/10/26 14:42
 */
public class SnatchListAdapter extends BaseListAdapter<SnatchPeriodBean.DataBean> {
    /**
     * 抢购中页面标识
     */
    public static final int BUYING = 0;
    /**
     * 抢购完成页面标识
     */
    public static final int BUYING_ENDING = 1;
    /**
     * 页面来源标识
     */
    private int flag = 0;
    /**
     * 用于退出 Activity,避免 Countdown，造成资源浪费。
     */
    private SparseArray<CountDownTimer> countDownCounters;

    private Context mContext;
    /**
     * 倒计时完成监听
     */
    private OnRefrushDataListener refrushDataListener;

    public SnatchListAdapter(Context context, int flag) {
        super(context);
        this.flag = flag;
        this.mContext = context;
        //初始化倒计时
        this.countDownCounters = new SparseArray<>();
    }

    /**
     * 倒计时结束后刷新数据监听
     *
     * @param context
     * @param flag
     * @param refrushDataListener 监听
     */
    public SnatchListAdapter(Context context, int flag, OnRefrushDataListener refrushDataListener) {
        super(context);
        this.flag = flag;
        this.mContext = context;
        this.refrushDataListener = refrushDataListener;
        //初始化倒计时
        this.countDownCounters = new SparseArray<>();
    }

    @Override
    public int getContentLayoutId() {
        return R.layout.adapter_buying_layout;
    }

    @Override
    public ViewHolder getViewHolder() {
        return new Holder();
    }

    public class Holder implements ViewHolder<SnatchPeriodBean.DataBean> {

        private ImageView iv_item_image;
        private TextView tv_item_title;
        private TextView tv_item_price_eth;
        private TextView tv_item_price_cny;
        private ProgressBar pb_item_progressBar;
        private TextView tv_item_remain;
        private TextView tv_item_price_unit;
        private LinearLayout ll_item_btn;
        private TextView tv_item_btn;
        private ImageView iv_item_btn_arrows;
        private LinearLayout ll_item_timer;
        private TextView tv_item_timer;
        private LinearLayout ll_snatch_contains;

        @Override
        public void initView(View view) {
            iv_item_image = view.findViewById(R.id.iv_item_image);
            tv_item_title = view.findViewById(R.id.tv_item_title);
            tv_item_price_eth = view.findViewById(R.id.tv_item_price_ETH);
            tv_item_price_cny = view.findViewById(R.id.tv_item_price_CNY);
            pb_item_progressBar = view.findViewById(R.id.pb_item_progressBar);
            tv_item_remain = view.findViewById(R.id.tv_item_remain);
            tv_item_price_unit = view.findViewById(R.id.tv_item_price_unit);
            ll_item_btn = view.findViewById(R.id.ll_item_btn);
            tv_item_btn = view.findViewById(R.id.tv_item_btn);
            iv_item_btn_arrows = view.findViewById(R.id.iv_item_btn_arrows);
            ll_snatch_contains = view.findViewById(R.id.ll_snatch_contains);
            //倒计时
            ll_item_timer = view.findViewById(R.id.ll_item_timer);
            tv_item_timer = view.findViewById(R.id.tv_item_timer);

            //剩余份数颜色控制
            tv_item_remain.setTextColor(ColorUtil.getColor(mContext, flag == BUYING ?
                    R.color.color_buying_remain : R.color.color_999999));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void initData(SnatchPeriodBean.DataBean data) {
            setShowStatus(data.getSTATUS(), data);
            pb_item_progressBar.setProgress(data.getBoughtNum() * 100 / data.getGoodsNum());
            //图片
            LKUtil.getImageLoader().loadImage(data.getGoodsImg(), iv_item_image, R.mipmap.icon_snatch_def);
            //title
            if (TextUtils.equals(data.getGoodsId(), "1")) {
                tv_item_title.setText("新人专属活动(每位用户仅限一次)");
            } else {
                tv_item_title.setText("第" + data.getPeriodNo() + "期");
            }

            //价格
            tv_item_price_eth.setText(data.getGoodsName());
            //单价
            String text = data.getGoodsPrice() + "BGT/份";
            SpannableString content = MyTextUtils.getInstance().setAutoTextSize(text, 1, text.length(), ScreenUtils.spToPx(mContext, 12));
            tv_item_price_unit.setText(content);
            //倒计时
            initCountDownTimer(tv_item_timer, ll_item_timer, DateUtils.getLongTime(data.getStartTime(), DateUtils.FORMAT_YMDHMS));
            //价值
            tv_item_price_cny.setText("≈" + data.getGoodsCost() + "元");
        }

        @Override
        public void initEvent(final SnatchPeriodBean.DataBean data) {
            ll_snatch_contains.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String btnText = tv_item_btn.getText().toString().trim();
                    if (TextUtils.equals(btnText, "即将开始")) {
                        Toast.makeText(mContext, "该活动暂未开始, 请稍后...", Toast.LENGTH_SHORT).show();
                    } else if (!TextUtils.isEmpty(data.getInviteText()) && TextUtils.equals(data.getGoodsId(), "1")) {
                        //新人专享已经中奖一次
                        Toast.makeText(mContext, "每人仅限抢一次", Toast.LENGTH_SHORT).show();
                    } else {
                        IntentUtils.startAty(mContext, SnatchDetailsActivty.class, "SNATCH_DATA", data);
                    }
                }
            });
        }

        /**
         * 设置显示状态
         * <p>
         * 状态 10:未开始 20:进行中 30:待揭晓 40:已揭晓 -1:已下架
         */
        @SuppressLint("SetTextI18n")
        private void setShowStatus(int status, SnatchPeriodBean.DataBean data) {
            ll_item_timer.setVisibility(status == 10 ? View.VISIBLE : View.GONE);
            pb_item_progressBar.setVisibility(status == 20 ? View.VISIBLE : View.GONE);
            tv_item_price_unit.setSelected(!(status == 10));
            iv_item_btn_arrows.setVisibility(status == 40 ? View.GONE : View.VISIBLE);
            switch (status) {
                case 10:
                    tv_item_btn.setText("即将开始");
                    ll_item_btn.setBackgroundResource(R.mipmap.duobao_weikaishi_button);
                    tv_item_remain.setText("总计" + data.getGoodsNum() + "份");
                    tv_item_remain.setTextColor(Color.parseColor("#5856D0"));
                    break;
                case 20:
                    tv_item_btn.setText("立即抢购");
                    ll_item_btn.setBackgroundResource(R.mipmap.duobao_qianggou_button);
                    pb_item_progressBar.setProgress(data.getBoughtNum() / data.getGoodsNum());
                    tv_item_remain.setText("仅剩" + (data.getGoodsNum() - data.getBoughtNum()) + "份(共" + data.getGoodsNum() + "份）");
                    tv_item_remain.setTextColor(Color.parseColor("#FF5453"));
                    break;
                case 30:
                    tv_item_btn.setText("等待开奖");
                    ll_item_btn.setBackgroundResource(R.mipmap.duobao_qianggou_button);
                    tv_item_remain.setText("总计" + data.getGoodsNum() + "份(已抢光)");
                    break;
                case 40:
                    tv_item_btn.setText("已开奖");
                    ll_item_btn.setBackgroundResource(R.mipmap.duobao_yikaijiang);
                    tv_item_remain.setText("总计" + data.getGoodsNum() + "份(已抢光)");
                    break;
            }
        }
    }

    private void initCountDownTimer(final TextView view, final LinearLayout layout, long mTime) {
        if (layout.getVisibility() == View.GONE) {
            return;
        }
        CountDownTimer countDownTimer = countDownCounters.get(view.hashCode());
        if (countDownTimer != null) {
            //将复用的倒计时清除
            countDownTimer.cancel();
        }
        long timer = mTime;
        timer = timer - System.currentTimeMillis();
        Log.d("initCountDownTimer", "initCountDownTimer:  === " + timer);
        //expirationTime 与系统时间做比较，timer 小于零，则此时倒计时已经结束。
        if (timer > 0) {
            countDownTimer = new CountDownTimer(timer, 1000) {
                public void onTick(long millisUntilFinished) {
                    String timeText = DateUtils.secToTime(millisUntilFinished);
                    SpannableString spannableString = MyTextUtils.getInstance().setAutoTextBackGroundColor(timeText, "[0-9]{1,}", "#FF5353", "#FFFFFF");
                    view.setText(spannableString);
                }

                public void onFinish() {
                    layout.setVisibility(View.GONE);
                    //倒计时结束刷新数据
                    if (refrushDataListener != null) {
                        refrushDataListener.refrushData();
                    }
                }
            }.start();
            //将此 countDownTimer 放入list.
            countDownCounters.put(view.hashCode(), countDownTimer);
        } else {
            layout.setVisibility(View.GONE);
        }
    }

    /**
     * 清空当前 CountTimeDown 资源
     */
    public void cancelAllTimers() {
        if (countDownCounters == null) {
            return;
        }
        Log.e("TAG", "size :  " + countDownCounters.size());
        for (int i = 0, length = countDownCounters.size(); i < length; i++) {
            CountDownTimer cdt = countDownCounters.get(countDownCounters.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }

    public interface OnRefrushDataListener {
        void refrushData();
    }
}
